<?php
session_start();
require 'inc/util.php';
//require 'inc/classifier.php';


Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2;

$facebook = fb_authenticate();
$user = $facebook->getUser();

//permissions to ask the user
$params = array('scope' => 'user_birthday,user_religion_politics,user_relationships,user_relationship_details,user_hometown,user_location,user_likes,user_activities,user_interests,user_education_history,user_work_history,user_online_presence,user_website,user_groups,user_events,user_photos,user_videos,user_photo_video_tags,user_notes,user_about_me,user_status,friends_birthday,friends_religion_politics,friends_relationships,friends_relationship_details,friends_hometown,friends_location,friends_likes,friends_activities,friends_interests,friends_education_history,friends_work_history,friends_online_presence,friends_website,friends_groups,friends_events,friends_photos,friends_videos,friends_photo_video_tags,friends_notes,friends_about_me,friends_status,read_stream,user_checkins,friends_checkins');

// fields to retrieve for each user
$fields1 = 'name,first_name,last_name,username,gender,birthday,hometown,location,education,work,likes,groups,events,checkins,friends,photos,videos,feed';
$fields2 = 'name,first_name,last_name,username,gender,birthday,hometown,location,education,work,likes,groups,events,checkins,photos,videos,feed';


if ($user) {
    try {

        // Proceed knowing you have a logged in user who's authenticated.
        $current_session = $_SESSION;
        $acess_token = $facebook->getAccessToken();
        $user_details = get_user_details($user, $facebook, $fields1, $acess_token);

        if (get_num_friends($user, $facebook, $user_details) == 0){
            $user_details = get_user_details($user, $facebook, $fields1, $acess_token,0);
        }
    } catch (FacebookApiException $e) {
        error_log($e);
        $user = null;
    }
}

// Login or logout url will be needed depending on current user state.
if ($user) {
    $logoutUrl = $facebook->getLogoutUrl();
} else {

    $loginUrl = $facebook->getLoginUrl($params);
}
?>


<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
    <head>
        <title>WINO Facebook Connect</title>
        <link rel="stylesheet" href="css/style.css" />
        <script type="text/javascript" src="js/utils.js"></script>
    </head>
    <body>
        <div style="text-align:center">
            <img src="images/logo.png" height="200" alt="If you don't see this image you have disabled images in your browser. WHY????" />
        </div>

        <?php if ($user):
            $nfriends = get_num_friends($user, $facebook, $user_details); ?>
            <h1>Step 1</h1>
            <div id="main">
                <div id="title">
                    <p>How many friends do you want to classify? (the more you take, the longer it will take to compute the results)
                </div>
                <form name="start" method ="post" action ="<?php $_SERVER['PHP_SELF']; ?>" >
                    <div id="filler"></div>
                    <div id="choices">
                    <?php if ($nfriends >= 5): ?>
                        <input type="radio" name="numfriends" value="5" checked="true" />5 friends (this should be fast)<br />
                    <?php else: ?>
                            <input type="radio" name="numfriends" value="<?php echo $nfriends ?>" checked="true" /><?php echo $nfriends ?> friends (this should be fast)<br />
                    <?php endif ?>
                    <?php if ($nfriends >= 10): ?>
                                <input type="radio" name="numfriends" value="10" />10 friends (this should take a few minutes)<br />
                    <?php endif ?>
                    <?php if ($nfriends >= 20): ?>
                                    <input type="radio" name="numfriends" value="20" />20 friends (this could take a while)<br />
                    <?php endif ?>
                                    <input type="radio" name="numfriends" value="<?php echo floor($nfriends / 2) ?>" /><?php echo floor($nfriends / 2) ?> friends (about half of your friends)<br />
                                    <input type="radio" name="numfriends" value="<?php echo $nfriends ?>" />All your friends (this might never end)<br /><br />
                                </div>
                                <div id="filler"></div>

                                <input type ="submit" name ="start" value ="Start" class="large awesome blue" onclick="return loadSubmit()" />
                                <div id="loading">
                                    <p id="progress"><img id="progress_image" style="padding-left:5px;padding-top:5px;" src="images/ajax-loader.gif" alt=""><br /><b>Downloading the Internet</b><br />
                                        <small>While you wait for the computation to complete, you want to watch <a href="http://www.phdcomics.com/movie/" target="_blank">this movie trailer</a>.</small></p>
                                </div>
                            </form>
                            <hr>
                            <p>
                                <a href ="model.php"target="_blank">Run Learner & Classifier</a> | <a href ="label.php"target="_blank">Label My Friends</a> |  <a href="<?php echo $logoutUrl; ?>">Logout</a>
                            </p>
            <?php else: ?>
                                        <div id="main">
                                            <p style="text-align: justify; padding: 1em">Welcome to <b>WINO</b>, a Facebook application that will help you understand the value of friendship.
                                                <b>What do we mean by this?</b> WINO will try to tell which friends of yours are people you are actually friend with, acquaintances or people you don't know.
                                                <b>Can you participate?</b> Of course! Just login with Facebook using the button below and go through these simple 3 steps:</p>
                                            <div id="filler"></div>
                                            <div id="steps">
                                                <div id="stepwrap">
                                                <div id="number">1</div><div id="step">Select a number of friends on which to run the test.</div>
                                                </div>
                                                <div id="stepwrap">
                                                <div id="number">2</div><div id="step">Tell WINO how close you are with the friends listed.</div>
                                                </div>
                                                <div id="stepwrap">
                                                <div id="number">3</div><div id="step">See how many WINO got right (but remember that machine learning is art, not science).</div>
                                                </div>
                                                

                                            </div>

                                            <div id="filler"></div>
                                            <p><small><b>If you are worried about your privacy, we are not storing any sensitive data.</b></small></p>
                                            <p>
                                                <a href="<?php echo $loginUrl; ?>" class="large awesome blue">Login with Facebook</a>
                                            </p>
                                        </div>
            <?php endif ?>

            <?php
                                        if (($user) && isset($_POST['start']) && isset($_POST['numfriends']) && $_POST['numfriends'] > 0 && $_POST['numfriends'] <= get_num_friends($user, $facebook, $user_details)) {
                                            $num = $_POST['numfriends'];

                                            $friends = get_friends_name_and_id($user, $facebook, $user_details);
                                            $rand_ids = array_rand($friends, $num);

                                            $num_friends = get_num_friends($user, $facebook, $user_details);
                                            //$friend_ids = get_friend_ids($user, $facebook, $user_details);
                                            //$friend_names = get_friend_names($user, $facebook, $user_details);
                                            $like_ids = get_like_ids($user, $facebook, $user_details);
                                            $group_ids = get_group_ids($user, $facebook, $user_details);
                                            $photo_tag_ids = get_photo_tag_ids($user, $facebook, $user_details);
                                            $video_tag_ids = get_video_tag_ids($user, $facebook, $user_details);
                                            $checkin_ids = get_checkin_ids($user, $facebook, $user_details);
                                            $event_ids = get_event_ids($user, $facebook, $user_details);
                                            //$gender_list =get_friends_gender($user, $facebook, $user_details);
                                            $feed_ids = get_feed_interactions($user, $facebook, $user_details);
                                            $employer_ids = get_employer_ids($user, $facebook, $user_details);
                                            $school_ids = get_school_ids($user, $facebook, $user_details);
                                            $features = array(array()); // this array of features stores all values

                                            $feature_file_path = "results/features_$user.csv";
                                            $feature_file = fopen($feature_file_path, 'w');
                                            $comma = ',';

                                            for ($i = 0; $i < $num; $i++) {
                                                $current_id = $rand_ids[$i];

                                                $done = false;
                                                $limit = 1000;

                                                while (!$done) {
                                                    try {
                                                        //skip friends that could not be downloaded
                                                        if (strcmp($friends[$current_id], "h") == 0) {
                                                            $done = true;
                                                        } else {
                                                            $friend_details = get_user_details($current_id, $facebook, $fields2, $acess_token, $limit);
                                                            $num_common_likes = get_num_common($like_ids, get_like_ids($current_id, $facebook, $friend_details));
                                                            $num_common_groups = get_num_common($group_ids, get_group_ids($current_id, $facebook, $friend_details));
                                                            $num_common_photo_tags = get_num_common($photo_tag_ids, get_photo_tag_ids($current_id, $facebook, $friend_details));
                                                            $num_common_video_tags = get_num_common($video_tag_ids, get_video_tag_ids($current_id, $facebook, $friend_details));
                                                            $num_common_checkins = get_num_common($checkin_ids, get_checkin_ids($current_id, $facebook, $friend_details));
                                                            $num_common_events = get_num_common($event_ids, get_event_ids($current_id, $facebook, $friend_details));
                                                            $conversation_count = count_conversation($user, $feed_ids, $current_id, get_feed_interactions($current_id, $facebook, $friend_details));
                                                            $num_common_schools = get_num_common($school_ids, get_school_ids($current_id, $facebook, $friend_details));
                                                            $num_common_employers = get_num_common($employer_ids, get_employer_ids($current_id, $facebook, $friend_details));
                                                            $num_common_friends = getMutualFriends($facebook, $user, $current_id);

                                                            //normalization step
                                                            $normalized_friends = $num_common_friends / $num_friends;
                                                            $normalized_likes = normalize($num_common_likes, $like_ids);
                                                            $normalized_groups = normalize($num_common_groups, $group_ids);
                                                            $normalized_photo_tags = normalize($num_common_photo_tags, $photo_tag_ids);
                                                            $normalized_video_tags = normalize($num_common_video_tags, $video_tag_ids);
                                                            $normalized_checkins = normalize($num_common_checkins, $checkin_ids);
                                                            $normalized_events = normalize($num_common_events, $event_ids);
                                                            $normalized_feed = normalize($conversation_count, $feed_ids);
                                                            $normalized_schools = normalize($num_common_schools, $school_ids);
                                                            $normalized_works = normalize($num_common_employers, $employer_ids);

                                                            array_push($features, array($friends[$current_id], $normalized_friends, $normalized_likes, $normalized_groups, $normalized_photo_tags, $normalized_video_tags, $normalized_checkins, $normalized_events, $normalized_feed, $normalized_schools, $normalized_works));

                                                            //write csv of features to file
                                                            $wres = fwrite($feature_file, $friends[$current_id] . $comma . $normalized_friends . $comma . $normalized_likes . $comma . $normalized_groups . $comma . $normalized_photo_tags . $comma . $normalized_video_tags . $comma . $normalized_checkins . $comma . $normalized_events . $comma . $normalized_feed . $comma . $normalized_schools . $comma . $normalized_works . "\n");
                                                            

                                                            if ($wres) {
                                                                $done = true;
                                                            }
                                                        }
                                                    } catch (FacebookApiException $exc) {
                                                        if ($limit == 0) {
                                                            $limit = 1000;
                                                        } else {
                                                            if ($limit > 2) {
                                                                $limit = $limit / 2;
                                                            } else {
                                                                //give up
                                                                fb_authenticate();
                                                                $done = true;
                                                            }
                                                        }

                                                        echo "<p style=\"font-color: red\">Problems getting the data of $friends[$current_id]. Limit reduced to $limit</p>";
                                                    }
                                                }
                                            }
                                            //display feature vectors for checkup
//                    foreach ($features as $index => $sub) {
//                        foreach ($sub as $k => $v) {
//                            echo $v . ",";
//                        }
//                        echo "<br>";
//                    }

                                            fclose($feature_file);

                                            $_SESSION["features"] = $feature_file_path;
                                            $_SESSION["friends"] = $friends;
                                            $_SESSION["rand_ids"] = $rand_ids;

                                            echo '<META HTTP-EQUIV="Refresh" Content="0; URL=results.php">';
                                        }
            ?>
        </div>
    </body>
</html>
